package org.linlinjava.litemall.admin.service;

import com.pdd.pop.sdk.http.api.request.*;
import com.pdd.pop.sdk.http.api.response.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.util.StringUtils;
import org.linlinjava.litemall.admin.config.PddConfig;
import org.linlinjava.litemall.admin.util.Base64ImgUtils;
import org.linlinjava.litemall.core.util.RedisUntil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.api.request.PddGoodsAddRequest.CarouselVideoItem;
import com.pdd.pop.sdk.http.api.request.PddGoodsAddRequest.ElecGoodsAttributes;
import com.pdd.pop.sdk.http.api.request.PddGoodsAddRequest.GoodsPropertiesItem;
import com.pdd.pop.sdk.http.api.request.PddGoodsAddRequest.OverseaGoods;
import com.pdd.pop.sdk.http.api.request.PddGoodsAddRequest.SkuListItem;
import com.pdd.pop.sdk.http.api.request.PddGoodsAddRequest.SkuListItemOverseaSku;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import sun.misc.BASE64Encoder;

import javax.net.ssl.HttpsURLConnection;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class AdminPddService {
    private final Log logger = LogFactory.getLog(AdminPddService.class);

    @Autowired
    private LitemallGoodsService litemallGoodsService;
    @Autowired
    private LitemallGoodsProductService litemallGoodsProductService;
    @Autowired
    private LitemallGoodsSpecificationService litemallGoodsSpecificationService;
    @Autowired
    private LitemallGoodsAttributeService litemallGoodsAttributeService;
    @Autowired
    private LitemallCategoryService litemallCategoryService;

    public Object goodsAdd(Integer goodsId) throws Exception {


        LitemallGoods  litemallGoods = litemallGoodsService.findById(goodsId);
        if(litemallGoods==null)
            return ResponseUtil.ok("商品未查询到");
        List<LitemallGoodsSpecification> specificationList = litemallGoodsSpecificationService.queryByGid(goodsId);

        List<LitemallGoodsProduct>  productsList = litemallGoodsProductService.queryByGid(goodsId);

        List<LitemallGoodsAttribute>  attributeList = litemallGoodsAttributeService.queryByGid(goodsId);


        PddGoodsAddRequest request = new PddGoodsAddRequest();
        //request.setBadFruitClaim(0);  //坏果包赔.
        //request.setBuyLimit(0L);  //限购次数
       // List<String> carouselGallery = new ArrayList<String>();

       // carouselGallery.add(litemallGoods.getGallery());
        //图片上传接口有问题，去掉上传
//        List<String> galleryList = new ArrayList<>();
//        for (int m=0;m<litemallGoods.getGallery().length;m++){
//            PddGoodsImageUploadResponse imgResponse = this.uploadImg2Pdd(litemallGoods.getGallery()[m]);
//            if(imgResponse.getGoodsImageUploadResponse()!=null){
//                galleryList.add(imgResponse.getGoodsImageUploadResponse().getImageUrl());
//            }else {
//                logger.info("上传图片失败:::"+imgResponse.getErrorResponse().getErrorMsg());
//            }
//
//        }
        request.setCarouselGallery(Arrays.asList(litemallGoods.getGallery()));//商品轮播图

       // List<CarouselVideoItem> carouselVideo = new ArrayList<CarouselVideoItem>();

       // CarouselVideoItem item = new CarouselVideoItem();
        //item.setFileId(0L);
       // item.setVideoUrl("str");
       // carouselVideo.add(item);
        //request.setCarouselVideo(carouselVideo);
        request.setCarouselVideoUrl(litemallGoods.getMainVedio()!=null?litemallGoods.getMainVedio():null);//视频

        LitemallCategory litemallCategory = litemallCategoryService.findById(litemallGoods.getCategoryId());
        if(litemallCategory==null)
            return ResponseUtil.ok("未获取到分类信息");

        PddGoodsCatsGetResponse levelResponse = this.getGoodscatL4(litemallCategory.getPddCateId().longValue());

//        if(levelResponse.getGoodsCatsGetResponse()==null)
//            return ResponseUtil.ok("获取拼多多分类失败");
//        for (int i=0;i<levelResponse.getGoodsCatsGetResponse().getGoodsCatsList().size();i++){
//            if(levelResponse.getGoodsCatsGetResponse().getGoodsCatsList().get(i).getCatName().equals(litemallCategory.getName())) {
//                request.setCatId(levelResponse.getGoodsCatsGetResponse().getGoodsCatsList().get(i).getCatId());
//                break;
//            }
//            logger.info("未能匹配的叶子类目id,3级类目id：：："+litemallCategory.getPddCateId());
//            return ResponseUtil.ok("叶子类目信息不全");
//        }
        if(litemallCategory.getSubCateId()==null){

            logger.info("此分类还未同步叶子分类信息，先同步叶子分类");
            return ResponseUtil.ok("此分类还未同步叶子分类信息");
        }

        request.setCatId(litemallCategory.getSubCateId());

        request.setCostTemplateId(84570829494603L);//默认选择的模板id
        request.setCountryId(0);//仅仅在海淘商品时生效，此处直接写0
        //request.setCustomerNum(0L);//团购人数
        //request.setCustoms("str");
        request.setDeliveryOneDay(0);


      //  List<String> detailGallery = new ArrayList<>();
        List<String> detailimgList = this.extractImgUrl(litemallGoods.getDetail());
//        for (int m=0;m<detailimgList.size();m++){
//            PddGoodsImageUploadResponse imgResponse = this.uploadImg2Pdd(detailimgList.get(m));
//            if(imgResponse.getGoodsImageUploadResponse()!=null){
//                detailGallery.add(imgResponse.getGoodsImageUploadResponse().getImageUrl());
//            }else {
//                logger.info("上传商品详情图片失败:::"+imgResponse.getErrorResponse().getErrorMsg());
//            }
//
//        }
        request.setDetailGallery(detailimgList);//商品详情图
        //卡券类商品属性
//        ElecGoodsAttributes elecGoodsAttributes = new ElecGoodsAttributes();
//        elecGoodsAttributes.setBeginTime(0L);
//        elecGoodsAttributes.setDaysTime(0);
//        elecGoodsAttributes.setEndTime(0L);
//        elecGoodsAttributes.setTimeType(0);
//        request.setElecGoodsAttributes(elecGoodsAttributes);

        request.setGoodsDesc(litemallGoods.getBrief());
        request.setGoodsName(litemallGoods.getName());

        /**
         * 此处待修改
         * */
     /***   List<GoodsPropertiesItem> goodsProperties = new ArrayList<GoodsPropertiesItem>();

        GoodsPropertiesItem item1 = new GoodsPropertiesItem();
        item1.setGroupId(0);
        item1.setImgUrl("str");
        item1.setNote("str");
        item1.setParentSpecId(0L);
        item1.setSpecId(0L);
        item1.setTemplatePid(0L);
        item1.setValue("str");
        item1.setValueUnit("str");
        item1.setVid(0L);
        goodsProperties.add(item1);
        request.setGoodsProperties(goodsProperties);*/



        request.setGoodsType(1);//国内普通商品


//        PddGoodsImageUploadResponse imgUrlResponse = this.uploadImg2Pdd(litemallGoods.getPicUrl());
//        if(imgUrlResponse.getErrorResponse()!=null){
//            logger.info("上传主图失败:::"+imgUrlResponse.getErrorResponse().getErrorMsg());
//            return ResponseUtil.ok("上传主图失败");
//        }
    //    request.setImageUrl(imgUrlResponse.getGoodsImageUploadResponse().getImageUrl());//商品主图
        request.setImageUrl(litemallGoods.getPicUrl());
       // request.setInvoiceStatus(false);//是否支持开票
        request.setIsCustoms(false);//是否上报海关

        request.setIsFolt(true); //是否支持假一赔十

        request.setIsPreSale(false);//是否预售
        request.setIsRefundable(true);//是否支持七天无理由退货
        request.setLackOfWeightClaim(0);//缺重量包退
        //request.setMaiJiaZiTi("str");//买家自提模板

       // request.setOrderLimit(0); //单次限量
       // request.setOriginCountryId(0);
        request.setOutGoodsId(litemallGoods.getAlibabaProductid().toString());

//        OverseaGoods overseaGoods = new OverseaGoods();
//        overseaGoods.setBondedWarehouseKey("str");
//        overseaGoods.setConsumptionTaxRate(0);
//        overseaGoods.setCustomsBroker("str");
//        overseaGoods.setHsCode("str");
//        overseaGoods.setValueAddedTaxRate(0);
//        request.setOverseaGoods(overseaGoods);
     //   request.setOverseaType(0);
      //  request.setPreSaleTime(0L);
     //   request.setQuanGuoLianBao(0);
        request.setSecondHand(false);
     //   request.setShangMenAnZhuang("str");
        request.setShipmentLimitSecond(172800L);

        /**
         * sku信息
         * */

        Long marketPrice = litemallGoods.getRetailPrice().multiply(new BigDecimal(150)).longValue();
        if(litemallGoods.getCounterPrice().intValue()>0)
            marketPrice= litemallGoods.getCounterPrice().multiply(new BigDecimal(100)).longValue();


        List<SkuListItem> skuList = new ArrayList<SkuListItem>();
        for(LitemallGoodsProduct litemallGoodsProduct:productsList) {


            SkuListItem item2 = new SkuListItem();
            item2.setIsOnsale(1);
            //item2.setLength(0L);
            item2.setLimitQuantity(999L);
            item2.setMultiPrice(litemallGoodsProduct.getPrice().multiply(new BigDecimal(100)).longValue());
            item2.setOutSkuSn(litemallGoodsProduct.getAlibabaSpecid());//商品外部编码，此处用的直接是阿里巴巴变的sku编码


//            for (int i = 0; i < litemallGoodsProduct.getSpecifications().length; i++) {
//                SkuListItemOverseaSku overseaSku = new SkuListItemOverseaSku();
//                overseaSku.setMeasurementCode(this.getUnitCode(litemallGoods.getUnit()));
//                overseaSku.setSpecifications("str");
//                overseaSku.setTaxation(0);
//            }
//
//
//            item2.setOverseaSku(overseaSku);
            item2.setPrice(litemallGoodsProduct.getPrice().multiply(new BigDecimal(110)).longValue());
            if(marketPrice<litemallGoodsProduct.getPrice().multiply(new BigDecimal(110)).longValue())
                marketPrice= litemallGoodsProduct.getPrice().multiply(new BigDecimal(150)).longValue();
            item2.setQuantity(litemallGoodsProduct.getNumber().longValue());
            String str = "[";
            if(litemallGoodsProduct.getSpecificationName()==null||litemallGoodsProduct.getSpecificationName().length<1||litemallGoodsProduct.getSpecificationName().length!=litemallGoodsProduct.getSpecifications().length){
                this.updateSpecificationName(goodsId);
              return ResponseUtil.ok("请再执行一次同步");
            }

            for (int i = 0; i < litemallGoodsProduct.getSpecifications().length; i++) {

                PddGoodsSpecIdGetResponse getIdresponse=  this.getPopClient(Long.valueOf(litemallCategory.getPddCateId()),litemallGoodsProduct.getSpecificationName()[i],litemallGoodsProduct.getSpecifications()[i]);
                    if(getIdresponse.getGoodsSpecIdGetResponse()!=null){
                        str+=getIdresponse.getGoodsSpecIdGetResponse().getSpecId();
                        if(i<litemallGoodsProduct.getSpecifications().length-1)
                            str+=",";
                    }else {
                        logger.info("获取自定义规格值失败:失败原因:"+getIdresponse.getErrorResponse().getErrorMsg());
                    }
            }
            str+="]";
            item2.setSpecIdList(str);
            String specificalImgurl = litemallGoods.getPicUrl();
            if(litemallGoodsProduct.getUrl()!=null)
                specificalImgurl=litemallGoodsProduct.getUrl();
//            PddGoodsImageUploadResponse specificationImgResponse = this.uploadImg2Pdd(specificalImgurl);
//            if(specificationImgResponse.getErrorResponse()!=null){
//                logger.info("上传规格预览图失败::::"+specificationImgResponse.getErrorResponse().getErrorMsg());
//                return ResponseUtil.ok("上传规格预览图失败");
//            }
           // item2.setThumbUrl(specificationImgResponse.getGoodsImageUploadResponse().getImageUrl());
            item2.setThumbUrl(specificalImgurl);
            item2.setWeight(litemallGoods.getFreight()!=null?litemallGoods.getFreight().longValue():0L);
            skuList.add(item2);
        }
        request.setMarketPrice(marketPrice);//市场价格单位为分
        request.setSkuList(skuList);

       // request.setSongHuoAnZhuang("str");
       // request.setSongHuoRuHu("str");
        //request.setTinyName("str");
        //request.setWarehouse("str");
        //request.setWarmTips("str");
        //request.setZhiHuanBuXiu(0);

        PddGoodsAddResponse response = this.createPopClient().syncInvoke(request, PddConfig.ACCESS_TOKEN_1);
        if(response.getErrorResponse()!=null) {
            logger.info(response.getErrorResponse().getErrorMsg());
        return ResponseUtil.ok(response.getErrorResponse().getErrorMsg());
        }
        litemallGoods.setPddGoodsId(response.getGoodsAddResponse().getGoodsId().intValue());
        litemallGoods.setPddGoodsCommentId(response.getGoodsAddResponse().getGoodsCommitId().intValue());
        litemallGoodsService.updateById(litemallGoods);
        return ResponseUtil.ok("同步成功");
    }

    /**
     *
     *
     * */

    public void  updateCateList() throws Exception {
        List<LitemallCategory> list = litemallCategoryService.getAll();
        for(LitemallCategory category:list){
            PddGoodsCatsGetResponse response = this.getGoodscatL4(category.getPddCateId().longValue());

            for (int i=0;i<response.getGoodsCatsGetResponse().getGoodsCatsList().size();i++){
                if(response.getGoodsCatsGetResponse().getGoodsCatsList().get(i).getCatName().equals(category.getName())) {
                   // request.setCatId(response.getGoodsCatsGetResponse().getGoodsCatsList().get(i).getCatId());
                    category.setSubCateId(response.getGoodsCatsGetResponse().getGoodsCatsList().get(i).getCatId());
                    litemallCategoryService.updateById(category);
                    break;
                }
                logger.info("未能匹配的叶子类目id,3级类目id：：：");
            }
        }
    }

    public PddGoodsSpecIdGetResponse getPopClient(Long cat_id,String specName,String specValue) throws Exception {


        PddGoodsSpecGetResponse response= this.specRequest(cat_id);


        if(response.getGoodsSpecGetResponse()!=null){

            Long parentSpecId = 0L;

            for(int i=0;i<response.getGoodsSpecGetResponse().getGoodsSpecList().size();i++){

                if(response.getGoodsSpecGetResponse().getGoodsSpecList().get(i).getParentSpecName().equals(specName)){
                    parentSpecId=response.getGoodsSpecGetResponse().getGoodsSpecList().get(i).getParentSpecId();
                    break;
                }
              //  logger.info("拼多多获取的规格名称:::"+response.getGoodsSpecGetResponse().getGoodsSpecList().get(i).getParentSpecName());
                //logger.info("传入的规格名称:::::"+specName);
              //  logger.info("传入的规格名称在拼多多凭条未获取到");
            }

            PddGoodsSpecIdGetRequest request = new PddGoodsSpecIdGetRequest();
            request.setParentSpecId(parentSpecId);
            request.setSpecName(specValue);

            return this.createPopClient().syncInvoke(request, PddConfig.ACCESS_TOKEN_1);
        }else {
            logger.info("获取规格编码失败,失败原因"+response.getErrorResponse().getErrorMsg());
            return null;
        }


    }
    /**
     * 商品上下架
     * */
    public PddGoodsSaleStatusSetResponse saleStatusChange(LitemallGoods litemallGoods,int status) throws Exception {
        PddGoodsSaleStatusSetRequest request = new PddGoodsSaleStatusSetRequest();
        request.setGoodsId(litemallGoods.getPddGoodsId().longValue());
        request.setIsOnsale(status);// 0为下架，1 为上架
        return  this.createPopClient().syncInvoke(request, PddConfig.ACCESS_TOKEN_1);
    }
    /**
     * 删除下架的商品
     * */
    public PddDeleteGoodsCommitResponse deleteGoods(LitemallGoods litemallGoods) throws Exception {
        PddDeleteGoodsCommitRequest request = new PddDeleteGoodsCommitRequest();
        List<Long> goodsIds = new ArrayList<Long>();
        goodsIds.add(litemallGoods.getPddGoodsId().longValue());
        request.setGoodsIds(goodsIds);
       return this.createPopClient().syncInvoke(request, PddConfig.ACCESS_TOKEN_1);

    }


    /**
     *  根据三级catId 获取拼多多标准规格名称和编码
     *
     * */

    public PddGoodsSpecGetResponse specRequest(Long catId) throws Exception {

        PddGoodsSpecGetRequest request = new PddGoodsSpecGetRequest();
        request.setCatId(catId);
        return this.createPopClient().syncInvoke(request, PddConfig.ACCESS_TOKEN_1);
       // System.out.println(JsonUtil.transferToJson(response));
    }
    /**
     * 叶子类目id，4级 五级
     * */
    public PddGoodsCatsGetResponse getGoodscatL4(Long parent_cat_id) throws Exception {

        PddGoodsCatsGetRequest request = new PddGoodsCatsGetRequest();
        request.setParentCatId(parent_cat_id);
       return this.createPopClient().syncInvoke(request);
       // System.out.println(JsonUtil.transferToJson(response));
    }
    /**
     * 商品规格单位
     * */
    private String getUnitCode(String unit){
        String  code = "000";
        switch (unit){
            case "件":
                code = "011";
                break;
            case "条":
                code = "015";
                break;
            case "双":
                code = "025";
                break;

        }
        return code;
    }
    /**
     *
     * 根据product表的specifications 值更新 specifica_name值
     * */
    public  void  updateSpecificationName(Integer gid){
        List<LitemallGoodsProduct> products = litemallGoodsProductService.queryByGid(gid);
        List<LitemallGoodsSpecification> specifications = litemallGoodsSpecificationService.queryByGid(gid);
        for(LitemallGoodsProduct product:products){
            List<String> list= new ArrayList<>();
            for(int i =0 ; i<product.getSpecifications().length;i++){
               for(LitemallGoodsSpecification specification:specifications){
                   if(product.getSpecifications()[i].equals(specification.getValue())){
                       list.add(specification.getSpecification());
                       break;
                   }
               }
            }
            String[] str= new String[list.size()];
            product.setSpecificationName(list.toArray(str));
            litemallGoodsProductService.update(product);
        }

    }
/**
 * 上传商品图片
 * */
    public PddGoodsImageUploadResponse uploadImg2Pdd(String url) throws Exception {
        PddGoodsImageUploadRequest request = new PddGoodsImageUploadRequest();
        String imageUrl = Base64ImgUtils.ImageToBase64ByOnline(url);
       // Base64ImgUtils.Base64ToImage(imageUrl, "C:/Users/Administrator/Desktop/test2.jpg");
        //imageUrl = Base64ImgUtils.ImageToBase64ByLocal("C:/Users/Administrator/Desktop/test2.jpg");
        request.setImage(imageUrl);
        return  this.createPopClient().syncInvoke(request, PddConfig.ACCESS_TOKEN_1);

    }
    /**
     * 正则取出详情里面的图片
     * */
    private  List<String>  extractImgUrl(String detail){
        List<String>  detailGallery = new ArrayList<String>();
         Pattern ATTR_PATTERN = Pattern.compile("<img[^<>]*?\\ssrc=['\"]?(.*?)['\"]?\\s.*?>",Pattern.CASE_INSENSITIVE);

        if(StringUtils.hasText(detail)){
            Matcher matcher = ATTR_PATTERN.matcher(detail);

            while (matcher.find()) {
                detailGallery.add(matcher.group(1));
            }
         }
        if(detailGallery.size()>20)
            detailGallery = detailGallery.subList(0,20);//若详情图大于20，截取前20张
         return  detailGallery;
    }


    private PopClient createPopClient(){
        PopClient  popClient = new PopHttpClient(PddConfig.CILIENT_ID,PddConfig.CLIENT_SECRET);
        return popClient;
    }


    // 将网络图片转成Base64码， 此方法可以解决解码后图片显示不完整的问题
    public  String imgBase64(String imgURL) {
        ByteArrayOutputStream outPut = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        try {
            // 创建URL
            URL url = new URL(imgURL);
            // 创建链接
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);

            if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "fail";//连接失败/链接失效/图片不存在
            }
            InputStream inStream = conn.getInputStream();
            int len = -1;
            while ((len = inStream.read(data)) != -1) {
                outPut.write(data, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(outPut.toByteArray());
    }



}
